package com.cwf.common.utils.validator;

import com.cwf.common.enums.ResCodeEnum;
import com.cwf.common.exception.base.MyException;
import org.hibernate.validator.HibernateValidator;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import java.util.Set;

public class ValidatorUtil {


    /**
     * @description 类校验
     * @param	data  校验数据
     * @author  18068
     * @date    2023/1/6 8:42
     * @return
     */
    public static <T> void check(T data){
        Validator validator = Validation.byProvider(HibernateValidator.class).configure()
                .failFast(false)
                .buildValidatorFactory().getValidator();
        Set<ConstraintViolation<T>> validate = validator.validate(data);
        String message = "";

        for (ConstraintViolation<T> v : validate) {
            message +=v.getPropertyPath().toString()+v.getMessage()+";";
        }
        if (! message.equals("")){
            throw new MyException(message, ResCodeEnum.PARAM_ERR.getCode());
        }
    }


    /**
     * @description 类分组校验
     * @param	data  校验数据
     * @param	group 校验分组
     * @author  18068
     * @date    2023/1/6 8:42
     * @return
     */
    public static <T> void check(T data,Class group){
        Validator validator = Validation.byProvider(HibernateValidator.class).configure()
                .failFast(false)
                .buildValidatorFactory().getValidator();
        Set<ConstraintViolation<T>> validate = validator.validate(data, group);
        String message = "";

        for (ConstraintViolation<T> v : validate) {
            message +=v.getPropertyPath().toString()+v.getMessage()+";";
        }
        if (! message.equals("")){
            throw new MyException(message, ResCodeEnum.PARAM_ERR.getCode());
        }
    }


}
